import os
import re
from bs4 import BeautifulSoup


def remove_specific_tags(html_content):
    """移除HTML内容中指定的标签"""
    soup = BeautifulSoup(html_content, 'html.parser')

    # # 1. 只移除<h2>正文内容</h2>标签本身
    # h2_content = soup.find('h2', string='文章内容')
    # if h2_content:
    #     h2_content.decompose()
    #
    # # 1. 只移除<h2>正文内容</h2>标签本身
    # h2_content = soup.find('h2', string='正文链接')
    # if h2_content:
    #     h2_content.decompose()
    #
    # # 2. 移除所有<h1>标签及其内容
    # for h1 in soup.find_all('h1'):
    #     h1.decompose()

    for h1 in soup.find_all('h2'):
        h1.decompose()

    # # 4. 替换特定a标签的文本内容
    # target_a = soup.find('a', class_='px-6 py-2 hover:bg-primary/80 transition-colors')
    # if target_a and target_a.get_text(strip=True) == '业务介绍':
    #     target_a.string = '业务简介'



    return str(soup)


def process_html_files(root_dir):
    """处理目录及其子目录下的所有HTML文件"""
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.endswith('.html'):
                file_path = os.path.join(dirpath, filename)
                try:
                    # 读取文件内容
                    with open(file_path, 'r', encoding='utf-8') as file:
                        content = file.read()

                    # 处理HTML内容
                    new_content = remove_specific_tags(content)

                    # 如果内容有变化，则写回文件
                    if new_content != content:
                        with open(file_path, 'w', encoding='utf-8') as file:
                            file.write(new_content)
                        print(f"已处理: {file_path}")
                    else:
                        print(f"未修改(未找到匹配标签): {file_path}")
                except Exception as e:
                    print(f"处理文件 {file_path} 时出错: {str(e)}")


if __name__ == "__main__":


    process_html_files(r'D:\aGetDataFrom111111\中储发展股份有限公司网站\05党群工作\党群工作-中储')
    print("处理完成!")